/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useReducer, Fragment } from "react";
import { Button, Table, Modal, Input, Form, message, Select } from "antd";
import { getAdminUserList, getSetting } from "../../api/serve";
import { formatDate } from "../../util/tool";
import styles from "./index.module.scss";
import config from "../../configs/index";
import { connect } from "react-redux";
import {
  addCreateAdminUser,
  updateAdminUser,
  delAdminUser,
} from "../../api/serve";
const initState = {
  user: "",
  isModalOpen: false,
  id: "",
  roleData: config,
  role: "admin",
};

function adminRedcuer(state = initState, action) {
  if (action) {
    return { ...state, ...action };
  }
  return state;
}
function UserList({ auth }) {
  //因为每次点击添加上一次表单的数据还会保留 解决方法创建form利用useForm
  // const IN_State = {
  //   // 映射关系
  //   0: "普通管理员",
  //   0: "超级管理员",
  // };
  const [form] = Form.useForm();
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      align: "center",
    },
    {
      title: "姓名",
      dataIndex: "username",
      align: "center",
    },
    {
      title: "角色",
      dataIndex: "role",
      align: "center",
    },
    {
      title: "密码",
      dataIndex: "password",
      align: "center",
    },
    {
      title: "创建时间",
      dataIndex: "create_time",
      align: "center",
      render: (value) => {
        return formatDate(value, "YYYY-MM-DD hh:mm:ss");
      },
    },
    {
      title: "编辑",
      key: "action",
      align: "center",
      render: (_, record) => (
        <Fragment>
          {auth["/userlist"].update?.value && (
            <Button onClick={() => onUpdate(record)}>更新</Button>
          )}
          {auth["/userlist"].del?.value && (
            <Button danger onClick={() => delUser(record.id)}>
              删除
            </Button>
          )}
        </Fragment>
      ),
    },
  ];
  //删除用户
  function delUser(id) {
    delAdminUser({ id: id }, (res) => {
      for (let i = 0; i < state.user.length; i++) {
        if (id === state.user[i].id) {
          state.user.splice(i, 1);
          dispatch({
            user: [...state.user],
          });
          break;
        }
      }
    });
  }
  // 更新用户信息
  function onUpdate(row) {
    //进行判断那个是超级管理员进行更新
    showModel();
    form.setFieldsValue({
      username: row.username,
      password: row.password,
      role: row.role,
    });
    dispatch({
      id: row.id,
    });
  }
  const [state, dispatch] = useReducer(adminRedcuer, initState);
  const onFinish = (values) => {
    if (state.id === "") {
      addCreateAdminUser({ ...values, authority: "" }, (res) => {
        message.success("添加成功");
        getAdminUserList({ page: 1 }, (res) => {
          let data = [];
          data = res.data[0].data;
          dispatch({ user: data });
        });
        Hiddenpodel();
      });
    } else {
      updateAdminUser({ ...values, authority: "", id: state.id }, (res) => {
        message.success("更新成功");
        getAdminUserList({ page: 1 }, (res) => {
          let data = [];
          data = res.data[0].data;
          dispatch({ user: data });
          Hiddenpodel();
        });
      });
    }
  };
  // 分页
  const paginationProps = {
    hideOnSinglePage: true,
    pageSize: 10,
    total: 20,
    onChange: handleData,
  };
  // 显示弹窗
  function showModel() {
    dispatch({
      isModalOpen: true,
    });
  }
  // 隐藏弹窗
  function Hiddenpodel() {
    dispatch({
      isModalOpen: false,
    });
  }

  function handleData(page) {
    // 根据可以传递过来的pqge数进行请求不同页的接口
    getAdminUserList({ page: page }, (res) => {
      let data = [];
      data = res.data[0].data;
      data.forEach((item, index) => {
        if (item.role === "0") {
          item = { ...item, role: "普通管理员" };
          data[index] = item;
        } else if (item.role === "1") {
          item = { ...item, role: "超级管理员" };
          data[index] = item;
        }
      });
      dispatch({ user: data });
    });
  }

  useEffect(function () {
    init();
  }, []);
  const init = () => {
    getAdminUserList({ page: 1 }, (res) => {
      let data = [];
      data = res.data[0].data;
      dispatch({ user: data });
    });
    getSetting({ title: "role" }, (res) => {
      let data = res.data[0].data;
      if (data.length > 0) {
        let o = {};
        data.forEach((item) => {
          o[item.title] = item.content = JSON.parse(item.content);
        });
        dispatch({
          roleData: o,
        });
        return;
      }
    });
  };
  // console.log(state.roleData);
  const addAdmin = () => {
    form.setFieldsValue({
      username: "",
      password: "",
      role: "",
    });
    dispatch({
      id: "",
    });
    showModel();
  };
  const handleisOpen = () => {
    Hiddenpodel();
  };
  const changeRole = (values) => {
    console.log(values);
    // let obj = {
    //   role:value
    // };
  };

  return (
    <Fragment>
      <p>
        {auth["/userlist"].add?.value && (
          <Button type="primary" size="large" onClick={addAdmin}>
            添加
          </Button>
        )}
      </p>
      <Table
        pagination={paginationProps}
        columns={columns}
        dataSource={state.user}
        rowKey="id"
      />
      <Modal
        title="添加管理员账户"
        open={state.isModalOpen}
        centered={true}
        footer={null}
        closable={false}
      >
        <Form
          name="basic"
          className={styles.Form}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          autoComplete="off"
          form={form}
        >
          <div className="login_con">
            <Form.Item
              name="username"
              rules={[
                {
                  required: true,
                  message: "请填写用户名",
                },
              ]}
            >
              <Input
                placeholder="username"
                disabled={state.id === "" ? false : true}
              />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请填写密码",
                },
              ]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请填写密码",
                },
              ]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请填写密码",
                },
              ]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请填写密码",
                },
              ]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请填写密码",
                },
              ]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请填写密码",
                },
              ]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请填写密码",
                },
              ]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请填写密码",
                },
              ]}
            >
              <Input placeholder="密码" />
            </Form.Item>
          </div>
          <Form.Item name="role" label="角色">
            <Select
              style={{ width: "100px" }}
              value={state.role}
              onChange={changeRole}
            >
              {Object.keys(state.roleData).map((item) => (
                <Select.Option value={item} key={item}>
                  {item}
                </Select.Option>
              ))}{" "}
            </Select>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit" className={styles.btn}>
              确认
            </Button>
            <Button type="primary" htmlType="button" onClick={handleisOpen}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Fragment>
  );
}
export default connect((state) => {
  let auth = {};
  if (state.user?.roleAuthority) {
    auth = JSON.parse(state.user.roleAuthority);
  }
  return { auth };
})(UserList);
